﻿module YazhiOP

open System.Diagnostics
open System.Runtime.InteropServices
open System
open System.Text
open System.Threading


[<DllImport("User32.dll")>]
extern IntPtr FindWindow(String lpClassName, String lpWindowName);

///如果多个名字雷同的窗口存在，多次相同的调用会返回不同的窗口，当程序页面上的操作导致雷同窗口在程序界面上隐藏或显出时
[<DllImport("User32.dll")>]
extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[<DllImport("User32.dll")>]
extern int SendMessage(IntPtr hWnd, int msg, int wParam, StringBuilder lParam);
[<DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)>]
extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);


let WM_LBUTTONDOWN = 0x201;
let WM_LBUTTONUP = 0x0202;
let WM_GETTEXT = 0x000D;
let WM_SETTEXT = 0x000C;
let WM_KEYDOWN = 0x0100;
let bufferLen = 1024;

////调试帮助之用  直接打印指针是显示10进制，spy++里面是16进制
//let tohex (i:nativeint) =
//    i.ToString("X")

///只有点击了make 以后才能调用。
///返回（contentLength,content)
let GetResultText()=
//路径是：
//    TfrmMain
//        TPage 
//            TPanel
//                TZSQRichEdit
    let yazhiWinH=
        FindWindow("TfrmMain","AGE Flash Packer 1.32 STD - [yazhi.fpp]")
    let tNotebook =FindWindowEx(yazhiWinH,IntPtr.Zero,"TNotebook","")
     //有两个page 第一个添加图片，第二个设置生成选项
    let tpage=FindWindowEx(tNotebook,IntPtr.Zero,"TPage",null)
    //cool!!!  正确使用FindwindowEx 第二个参数是要找子窗体的上一个子窗体
    //let tpage2=FindWindowEx(tNotebook,tpage,"TPage",null)
    let panel1 =FindWindowEx(tpage,IntPtr.Zero,"TPanel",null)
    let richEdit =FindWindowEx(panel1,IntPtr.Zero,"TZSQRichEdit",null)

    let sb = new StringBuilder(bufferLen)
    let retCode=SendMessage(richEdit, WM_GETTEXT, bufferLen,sb )
    (retCode,sb.ToString())


let ClickMakeBtn( btnName:string) =
    let yazhiWinH=
            FindWindow("TfrmMain","AGE Flash Packer 1.32 STD - [yazhi.fpp]")
    let makeBtn =FindWindowEx(yazhiWinH,IntPtr.Zero,"TButton",btnName)
    SendMessage(makeBtn,WM_LBUTTONDOWN,0,null) |>ignore
    //必须用POST 否则如果会弹出是否覆盖会阻塞方法返回
    PostMessage(makeBtn,WM_LBUTTONUP,IntPtr.Zero,IntPtr.Zero) |>ignore

///重复生成的时候，在按下生成按钮时会弹出是否重复生成窗体。这里写死重复生成。
let PassCheckBoxIFExist(btnName:string)=
    let ckb=FindWindow("#32770","操作确认")
    let btn =FindWindowEx(ckb,IntPtr.Zero,"Button",btnName)
    SendMessage(btn,WM_LBUTTONDOWN,0,null) |>ignore
    SendMessage(btn,WM_LBUTTONUP,0,null) |>ignore    
